﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using static Learun.Application.TwoDevelopment.ZZDT_EC.ProjectSugar;
using static Learun.Util.SqlSugar.SqlSugarHelper;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-02-24 11:10
    /// 描 述：对象类型
    /// </summary>
    public class ec_objecttypeBLL : ec_objecttypeIBLL
    {
        private ec_objecttypeService ec_objecttypeService = new ec_objecttypeService();

        #region 获取数据
        /// <summary>
        /// 查询对象类型的tree结构，具体深度有3个层级
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="dataType">0:对象类型、1:位号、2:图纸</param>
        /// <param name="KeyWork">关键字</param>
        /// <returns></returns>
        public List<TreeModel> GetObjectTypeData3Level(string projectId, string dataType, string KeyWord = "")
        {
            List<TreeModel> treeList = new List<TreeModel>();


            try
            {
                var ec_enginedataIBLL = new ec_enginedataBLL();
                var ec_enginedata_pixelBLL = new ec_enginedata_pixelBLL();
                //string queryJson = "{\"ProjectId\":\"" + projectId + "\"}";
                string queryJson = "{\"ProjectId\":\"" + projectId + "\"}";

                //获取对象类型树形数据
                var listObjectType = GetList(queryJson, null, true);
                //获取工程数据（位号+数据状态）
                List<ec_enginedataEntity> listEngineData = new List<ec_enginedataEntity>();
                //获取工程数据图元数据（图纸+句柄）
                List<ec_enginedata_pixelEntity> listPixel = new List<ec_enginedata_pixelEntity>();
                if (dataType.Equals("0") || dataType.Equals("1") || dataType.Equals("2"))
                {
                    if (dataType.Equals("0") && !string.IsNullOrEmpty(KeyWord))
                    {
                        string query = "{\"ProjectId\":\"" + projectId + "\",\"TagNumberFilter\":\"" + KeyWord + "\"}";
                        listEngineData = ec_enginedataIBLL.GetList(query).ToList();//查询位号的基础信息
                    }
                    if (dataType.Equals("1") || dataType.Equals("2"))
                    {
                        listEngineData = ec_enginedataIBLL.GetList(queryJson).ToList();//查询位号的基础信息
                    }
                }
                if (dataType.Equals("2"))
                {
                    listPixel = ec_enginedata_pixelBLL.GetList(queryJson).ToList();
                    listPixel = listPixel.Where(x => x.DeleteFlg != 1).ToList();
                }
                if (!string.IsNullOrEmpty(KeyWord))
                {
                    var objecttypeIds = listEngineData.Select(x => x.ObjectTypeID).Distinct().ToList();

                    List<string> fullIds = new List<string>();
                    foreach (var item in listObjectType.Where(x => objecttypeIds.Contains(x.ObjectTypeID)).ToList())
                    {
                        fullIds.AddRange(item.FullPath.Split(','));
                    }
                    fullIds = fullIds.Distinct().ToList();
                    listObjectType = listObjectType.Where(x => fullIds.Contains(x.ObjectTypeID)).ToList();
                }

                foreach (var item in listObjectType)
                {
                    TreeModel nodeCatalogue = new TreeModel();
                    nodeCatalogue.id = item.ObjectTypeID;
                    nodeCatalogue.text = item.ObjectTypeName;
                    nodeCatalogue.value = item.ObjectTypeID;
                    nodeCatalogue.nodeType = "0";
                    nodeCatalogue.showcheck = false;
                    nodeCatalogue.checkstate = 0;
                    nodeCatalogue.isexpand = false;
                    nodeCatalogue.parentId = item.UpObjectTypeID;
                    nodeCatalogue.NodeExtData = item;
                    treeList.Add(nodeCatalogue);
                    if (dataType.Equals("1") || dataType.Equals("2"))
                    {
                        var listEngineDataTmp = listEngineData.Where(x => x.ObjectTypeID == item.ObjectTypeID && x.TagNumber.Contains(KeyWord)).ToList();
                        foreach (var engineData in listEngineDataTmp)
                        {
                            TreeModel nodeEngineData = new TreeModel();
                            nodeEngineData.id = engineData.EngineDataID;
                            nodeEngineData.text = engineData.TagNumber + "(" + engineData.DataStatusName + ")";
                            nodeEngineData.value = engineData.EngineDataID;
                            nodeEngineData.nodeType = "1";
                            nodeEngineData.showcheck = false;
                            nodeEngineData.checkstate = 0;
                            nodeEngineData.isexpand = false;
                            nodeEngineData.parentId = item.ObjectTypeID;
                            nodeEngineData.NodeExtData = engineData;
                            treeList.Add(nodeEngineData);
                            if (dataType.Equals("2"))
                            {
                                var listPixelTmp = listPixel.Where(x => x.EngineDataID == engineData.EngineDataID);
                                if (listPixelTmp == null || listPixelTmp.Count() == 0)
                                {
                                    treeList.Remove(nodeEngineData);
                                    continue;
                                }
                                listPixelTmp = listPixelTmp.OrderBy(x => x.DrawingFileName).ToList();
                                foreach (var pixel in listPixelTmp)
                                {
                                    TreeModel nodeFile = new TreeModel();
                                    nodeFile.id = pixel.EngineDataPixelID;
                                    nodeFile.text = pixel.DrawingFileName + "(" + pixel.PixelCode + ")";
                                    nodeFile.value = pixel.DrawingFileID;
                                    nodeFile.nodeType = "2";
                                    nodeFile.showcheck = false;
                                    nodeFile.checkstate = 0;
                                    nodeFile.isexpand = false;
                                    nodeFile.parentId = engineData.EngineDataID;
                                    nodeFile.NodeExtData = pixel;
                                    treeList.Add(nodeFile);
                                }
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex, ex.Message + "※※※" + ex.StackTrace);
                }
            }
            return treeList.ToTree();
        }

        /// <summary>
        /// 查询对象类型
        /// </summary>
        /// <param name="queryJson"></param>
        /// <param name="pagination"></param>
        /// <param name="Extra">是否需要一些特定的内容，比如OPC等</param>
        /// <returns></returns>
        public IEnumerable<ec_objecttypeEntity> GetList(string queryJson, Pagination pagination = null, bool Extra = false)
        {
            try
            {
                var queryParam = queryJson.ToJObject();
                var ProjectId = queryParam["ProjectId"]?.ToString();
                var ObjectTypeIDs = queryParam["ObjectTypeIDs"]?.ToString();
                var keyword = queryParam["keyword"]?.ToString();
                var ObjectTypeID = queryParam["ObjectTypeID"]?.ToString();
                var FullPathCN = queryParam["FullPathCN"]?.ToString();
                var KeyWordAndDir = queryParam["KeyWordAndDir"]?.ToString();
                var CurObjectTypeID = queryParam["CurObjectTypeID"]?.ToString();

                var tableName = TableName<ec_objecttypeEntity>(ProjectId);

                var list = Db.Queryable<ec_objecttypeEntity>().AS(tableName).OrderBy(x => x.OrderID).ToList();
                if (Extra)
                {
                    
                    var opc = new ec_objecttypeEntity()
                    {
                        ObjectTypeID = "OPC",
                        ObjectTypeName = "OPC",
                        ObjectTypeNameEN = "OPC",
                        IsParent = "0",
                        UpObjectTypeID = "-1",
                        FullPathCN = "OPC",
                        FullPath = "OPC",
                        OrderID = 1001,
                        CreateUserID = "System",
                        CreateTime = DateTime.Now,
                        IsSerialNumber = 1
                    };

                    list.Add(opc);
                }
                list?.ForEach(x =>
                {
                    x.IsParent = list.Any(y => y.UpObjectTypeID == x.ObjectTypeID) ? "1" : "0";
                });
                if (!string.IsNullOrEmpty(ObjectTypeIDs))
                {
                    list = list.Where(x => ObjectTypeIDs.Split(',').Contains(x.ObjectTypeID)).ToList();
                }
                if (!string.IsNullOrEmpty(keyword))
                {
                    list = list.Where(x => x.ObjectTypeName.Contains(keyword) || x.ObjectTypeNameEN.Contains(keyword)).ToList();
                }
                if (!string.IsNullOrEmpty(ObjectTypeID))
                {
                    list = list.Where(x => x.ObjectTypeID == ObjectTypeID).ToList();
                }
                if (!string.IsNullOrEmpty(FullPathCN))
                {
                    list = list.Where(x => x.FullPathCN == FullPathCN).ToList();
                }
                if (!string.IsNullOrEmpty(KeyWordAndDir))
                {
                    List<string> ids = new List<string>();
                    list.Where(x => x.ObjectTypeName.Contains(KeyWordAndDir) || x.ObjectTypeNameEN.Contains(KeyWordAndDir))
                        .Select(x => x.FullPath).ToList().ForEach(x =>
                        {
                            ids.AddRange(x.Split(','));
                        });
                    list = list.Where(x => ids.Contains(x.ObjectTypeID)).ToList();
                }
                if (!string.IsNullOrEmpty(CurObjectTypeID))
                {
                    list = list.Where(x => !x.FullPath.Split(',').Contains(CurObjectTypeID)).ToList();
                }

                if (pagination != null)
                {
                    list = list.Skip(pagination.rows * (pagination.page - 1)).Take(pagination.rows).ToList();
                }
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_objecttypeEntity> GetTree(string queryJson)
        {
            try
            {
                return ec_objecttypeService.GetTree(queryJson);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_objecttypeEntity> GetListByProjectId(string queryJson)
        {
            try
            {
                return ec_objecttypeService.GetListByProjectId(queryJson);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_objecttypeEntity GetEntity(string keyValue, string ProjectId)
        {
            try
            {
                return ec_objecttypeService.GetEntity(keyValue, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, string ProjectId)
        {
            try
            {
                ec_objecttypeService.DeleteEntity(keyValue, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_objecttypeEntity entity, string ProjectId)
        {
            try
            {
                string fullPath = "";
                string fullPathCN = "";
                if (!string.IsNullOrEmpty(keyValue))
                {
                    entity.Modify(keyValue);
                    GetFullPath(ref fullPath, ref fullPathCN, entity.UpObjectTypeID, entity.ObjectTypeID, entity.ObjectTypeName, ProjectId);
                    entity.FullPath = fullPath;
                    entity.FullPathCN = fullPathCN;
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        Db.Updateable(entity);
                    }
                    else
                    {
                        var ProjectEntity = Db.Queryable<ec_projectEntity>().Single(x => x.ProjectId == ProjectId);
                        //处理下panel
                        //this.BaseRepository().FindEntity<ec_objecttypeEntity>($"SELECT * FROM ec_objecttype_{ProjectEntity.ProjectIndex} WHERE ObjectTypeID = '{keyValue}'", null);
                        var curEntity = SqlSugarHelper.Db.Ado.SqlQuerySingle<ec_objecttypeEntity>($"SELECT * FROM ec_objecttype_{ProjectEntity.ProjectIndex} WHERE ObjectTypeID = '{keyValue}'");
                        if (entity.SystemPanel == 1 && (curEntity.SystemPanel == null || curEntity.SystemPanel == 0))
                        {
                            //原来不是，现在是了
                            ec_PanelBLL ec_panelBll = new ec_PanelBLL();
                            //var EngineerDatas = this.BaseRepository().FindList<ec_enginedataEntity>($"select * from ec_enginedata_{ProjectEntity.ProjectIndex} t where t.ObjectTypeID = '{keyValue}' and not exists (select 'x' from ec_panel_{ProjectEntity.ProjectIndex} t1 where t1.EngineerDataID = t.EngineDataID)");
                            var EngineerDatas = SqlSugarHelper.Db.SqlQueryable<ec_enginedataEntity>($"select * from ec_enginedata_{ProjectEntity.ProjectIndex} t where t.ObjectTypeID = '{keyValue}' and not exists (select 'x' from ec_panel_{ProjectEntity.ProjectIndex} t1 where t1.EngineerDataID = t.EngineDataID)").ToList();
                            foreach (var EngineerData in EngineerDatas)
                            {
                                ec_panelBll.SaveEntity(ProjectId, "", new ec_PanelEntity()
                                {
                                    EngineerDataID = EngineerData.EngineDataID,
                                    Panel_Loc_ID = "1",
                                    MaxStripNumber = 0,
                                    PanelID = ""
                                });
                            }
                        }
                        else if (entity.SystemPanel == 0 && curEntity.SystemPanel == 1)
                        {
                            //原来是，现在不是了
                        }


                        //this.BaseRepository().UpdateByNoMap(entity, $"ec_objecttype_{ProjectEntity.ProjectIndex}", "ObjectTypeID");
                        Db.Updateable(entity).AS($"ec_objecttype_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }



                }
                else
                {
                    //yxh，自动给排序
                    if (entity.OrderID == -1)//前台ui是给不出的，是程序在前台的js里故意给的
                    {
                        string queryJsonForMaxOrder;
                        if (string.IsNullOrWhiteSpace(ProjectId))
                        {
                            queryJsonForMaxOrder = "{}";
                        }
                        else
                        {
                            queryJsonForMaxOrder = "{ProjectId:\"" + ProjectId + "\"}";
                        }
                        var MaxOrderID = this.GetList(queryJsonForMaxOrder).OrderByDescending(x => x.OrderID).Select(x => x.OrderID).First();
                        if (MaxOrderID == null)
                        {
                            entity.OrderID = 1;
                        }
                        else
                        {
                            entity.OrderID = MaxOrderID + 1;
                        }
                    }
                    entity.Create();
                    GetFullPath(ref fullPath, ref fullPathCN, entity.UpObjectTypeID, entity.ObjectTypeID, entity.ObjectTypeName, ProjectId);
                    entity.FullPath = fullPath;
                    entity.FullPathCN = fullPathCN;
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        Db.Insertable(entity).ExecuteCommand();
                    }
                    else
                    {
                        var ProjectEntity = Db.Queryable<ec_projectEntity>().Single(x => x.ProjectId == ProjectId);
                        //this.BaseRepository().InsertByNoMap(entity, $"ec_objecttype_{ProjectEntity.ProjectIndex}");
                        Db.Insertable(entity).AS($"ec_objecttype_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        #endregion
        /// <summary>
        /// 完整路径保存父级和子级的分类ID，用逗号分割
        /// </summary>
        /// <returns></returns>
        public void GetFullPath(ref string fullPath, ref string fullPathCN, string parentId, string id, string name, string ProjectId)
        {
            if (string.IsNullOrEmpty(parentId) || parentId == "0")
            {
                fullPath = id;
                fullPathCN = name;
            }
            else
            {
                var entity = GetEntity(parentId, ProjectId);
                fullPath = entity?.FullPath + "," + id;
                fullPathCN = entity?.FullPathCN + "/" + name;
            }
        }
    }
}
